<?php

namespace cmf\controller;

use think\Controller;
use think\Db;
use think\Response;
use think\exception\HttpResponseException;

class OpenApiBaseController extends Controller{
    protected $serverid;
    protected $server;
    protected function _initialize() {
        parent::_initialize(); 
        header('Access-Control-Allow-Origin:*');
        $token = $this->request->param('open_token');
        //$ss = '1';
        if(empty($token)){
            $login = $this->request->param('login_token');
            $time = $this->request->param('time');
            $ip = $this->request->ip();
            if($time< time()-30){
                $this->ajaxError(401,'操作超时');
            }
            if($login!=md5('da-lian-you-xia-ke-ji'.$time)){
                $this->ajaxError(401,'操作超时。请重新进入系统');
            }
            $sv = Db::name('server')->where('ip_s',$ip)->find();
            $this->server = $sv;
            $token = cmf_random_string(32);
            if(empty($sv)){
                $this->serverid = dmt_add_new_server($ip);
                $sv['id'] = $this->serverid;
                $this->server = $sv;
            }else{
                $this->serverid = $sv['id'];
                $sv['optoken']=$token;
                if(empty($sv['security_s'])){
                    $sv['security_s'] = cmf_random_string(32);
                    $sv['name_s']='自动生成';
                }
                Db::name('server')->update($sv);
            }
        }else{
            $sv = Db::name('server')->where('optoken',$token)->find();
            if(empty($sv)){
                $this->ajaxError(401,'操作超时。请重新进入系统');
            }
        }
        $this->server = $sv;
        $this->serverid = $sv['id'];
    }
    
    protected function ajaxError($code,$msg){
        if($code>0){
            send_http_status($code);
        }
        $result = [
            'code' => $code,
            'msg'  => $msg,
        ];
        $response = Response::create($result, 'json',$code);
        throw new HttpResponseException($response);
    }
    
    protected function ajaxSuccess($data,$msg=''){
        $result = [
            'code' => 0,
            'data'  => $data,
            'msg'  => $msg,
        ];
        
        $response = Response::create($result, 'json');
        throw new HttpResponseException($response);
    }
}
